<?php
namespace Wxapps\Model;
use Think\Model;
use Wxapps\Lib\WxUser;

class UsersModel extends Model{
    private $token;

    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        // 'create_time',
        // 'update_time',
        'password'
    ];

    /**
     * 获取用户信息
     * @param $token
     * @return null|static
     * @throws \think\exception\DbException
     */
    public function getUser($token)
    {
        $openid = S($token)['openid'];
        $info = $this->where(['openid' => $openid])->find();
        for($i = 0  ; $i < count($this->hidden);$i++){
            unset($user[$this->hidden[$i]]);
        }
        return $info;
    }

    /**
     * 用户登录
     * @param array $post
     * @return string
     * @throws BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function login($post)
    {
        // 微信登录 获取session_key
        $session = $this->wxlogin($post['code']);
        // 自动注册用户
        $refereeId = isset($post['referee_id']) ? $post['referee_id'] : null;
        $userInfo = json_decode(htmlspecialchars_decode($post['user_info']), true);
        $user_data = $this->register($session['openid'],$session['unionid'], $userInfo, $refereeId);
        // 生成token (session3rd)
        $this->token = $this->token($session['openid']);
        // 记录缓存, 7天
        S($this->token, $session, 86400 * 7);
        return $user_data;
    }

    /**
     * 获取token
     * @return mixed
     */
    public function getToken()
    {
        return $this->token;
    }

    /**
     * 微信登录
     * @param $code
     * @return array|mixed
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    private function wxlogin($code)
    {
        // 获取当前小程序信息
        $wxConfig = C('wx_config');
        // 验证appid和appsecret是否填写
        if (empty($wxConfig['app_id']) || empty($wxConfig['app_secret'])) {
            _apiReturn(0,'缺少小程序配置信息');
        }
        // 微信登录 (获取session_key)
        $WxUser = new WxUser($wxConfig['app_id'], $wxConfig['app_secret']);
        if (!$session = $WxUser->sessionKey($code)) {
            _apiReturn(0,$WxUser->getError());
        }
        return $session;
    }

    /**
     * 生成用户认证的token
     * @param $openid
     * @return string
     */
    private function token($openid)
    {
        // 生成一个不会重复的随机字符串
        $guid = uniqid();
        // 当前时间戳 (精确到毫秒)
        $timeStamp = microtime(true);
        // 自定义一个盐
        $salt = 'token_salt';
        return md5("{$timeStamp}_{$openid}_{$guid}_{$salt}");
    }

    /**
     * 自动注册用户
     * @param $open_id
     * @param $data
     * @param int $refereeId
     * @return mixed
     * @throws \Exception
     * @throws \think\exception\DbException
     */
    private function register($open_id,$unionid, $wxdata, $refereeId = null)
    {
        //需要转换一下wxdata，使得与数据库匹配
        $data = [
            "openid" => $open_id,
            "unionid" => $unionid,
            "nickname"=>$wxdata['nickName'],
            "role" => "base",
            "sex" => $wxdata['gender'],
            "city" => $wxdata['city'],
            "country"=>$wxdata['country'],
            "language" => $wxdata['language'],
            "province" => $wxdata['province'],
            "city"=>$wxdata['city'],
            "avatar"=>$wxdata['avatarUrl'],
            "headimgurl" => $wxdata['avatarUrl']
        ];
        // 查询用户是否已存在
        $user = $this->where(['openid'=>$open_id])->find();
        if(!$user){
            $data['create_time'] = $data['update_time'] = time();
            $data['id'] = $this->add($data); //写到数据库
            // $data['wechat_reg'] = 'NO';
            return $data;
        }else{
            // $user['wechat_reg'] = 'YES';
            return $user;
        }
    }

    /**
     * 用户列表
     */
    public function _query($p = 1 , $row = 10 , $query = ''){
        $sql = "SELECT * FROM mini_users WHERE 1=1 ";
        $sqlcount = "SELECT COUNT(DISTINCT `id`) AS tp_count FROM mini_users WHERE 1=1 ";
        if($query){
            $sql .= $query;
            $sqlcount .= $query;
        }
        //order
        $sql .= " ORDER BY create_time desc ";
        $sql .= " LIMIT ".($p-1)*$row.",".$row;
        $data['data'] = $this->query($sql);
        $total = $this->query($sqlcount);
        $data['page']['total'] = $total[0]['tp_count'];
        $data['page']['cur'] = $p;
        $data['page']['row'] = $row;
        // $data['sql'] = $sql;
        return $data;
    }
    /**
     * 修改手机号码
     */
    public function _update_mobile($post){
        // $openId = S($post['token'])['openid'];
        // if(!$openId){
        //     _apiReturn(0,'对不起，请先登陆',1);
        // }
        if(!$post['uid'] || !$post['mobile']){
            _apiReturn(0,'缺少参数',0);
        }
        if(!check_phone($post['mobile'])){
            _apiReturn(0,'手机号码格式错误');
        }
        $data = [
            'id'=>$post['uid'],
            'mobile' => $post['mobile'],
            'update_time' => time()
        ];
        if($this->save($data)){
            _apiReturn(1,'success');
        }else{
            _apiReturn(0,'系统错误，修改失败');
        }
    }

    /**
     * 保存用户数据
     */
    public function _update($post){
        if(!$post['uid']){
            _apiReturn(0,'请先登录');
        }

        $data = [
            'id'=>$post['uid'],
            'realname' => $post['realname'],
            'email' => $post['email'],
            'birth' => $post['birth'],
            'update_time' => Date('Y-m-d H:i:s')
        ];
        if($this->save($data)){
            _apiReturn(1,'success');
        }else{
            _apiReturn(0,'系统错误，修改失败');
        }

    }

    /**
     * 保存用户数据
     */
    public function _bing_wechat_user($post){

        if(!$post['password']){
            _apiReturn(0,'密码不能为空!','');
        }
        if(!$post['mobile']){
            _apiReturn(0,'手机号不能为空!','');
        }
        if(!$post['openid']){
            _apiReturn(0,'微信ID不能为空!','');
        }
        $password = md5($post['password']);
        $up_info = [
            'password'=>$password,
            'mobile' => $post['mobile'],
        ];
        $info = $this->where($up_info)->find();
        if($info){
            $openid_info['openid'] = $post['openid'];
            if ($this->where($up_info)->save($openid_info)) {
                $info['openid'] = $post['openid'];
                _apiReturn(1,'保存成功',$info);
            }else {
                _apiReturn(0,'绑定失败，请重试~','');
            }
        }else{
            _apiReturn(0,'绑定失败，请检查手机号或密码~','');
        }

    }

    /**
     * 手机号快速验证
     */
    public function _check_phone_number($post){
        // 获取当前小程序信息
        $wxConfig = C('wx_config');
        // 验证appid和appsecret是否填写
        if (empty($wxConfig['app_id']) || empty($wxConfig['app_secret'])) {
            _apiReturn(0,'缺少小程序配置信息');
        }
        // 获取手机手机信息
        $WxUser = new WxUser($wxConfig['app_id'], $wxConfig['app_secret']);
        if (!$phone_info = $WxUser->getPhoneNumber($post['code'])) {
            _apiReturn(0,$WxUser->getError(),$phone_info);
        }
  
        //将手机号更新到用户的信息里
        $this->save(['id'=>$post['uid'],'mobile'=>$phone_info['phone_info']['phoneNumber']]);
        
        _apiReturn(1,'success',$phone_info);

    }

}